import React, { useState } from 'react';
import { Card, Typography, Space, Tabs, Row, Col, Statistic, Progress, Tag, Tooltip, Badge, Divider } from 'antd';
import { 
  LineChartOutlined, 
  ArrowUpOutlined, 
  ArrowDownOutlined,
  UserOutlined,
  TeamOutlined,
  TrophyOutlined,
  CalendarOutlined,
  RiseOutlined,
  FallOutlined,
  StarOutlined,
  GlobalOutlined,
  MobileOutlined,
  DesktopOutlined,
  TabletOutlined
} from '@ant-design/icons';

const { Title, Text } = Typography;

interface UserTrendChartProps {
  loading?: boolean;
}

const UserTrendChart: React.FC<UserTrendChartProps> = ({ loading = false }) => {
  const [activeTab, setActiveTab] = useState('monthly');

  // 扩展的月度数据
  const monthlyData = [
    { month: '1月', users: 1200, newUsers: 180, activeUsers: 980, retention: 82 },
    { month: '2月', users: 1350, newUsers: 220, activeUsers: 1100, retention: 85 },
    { month: '3月', users: 1180, newUsers: 150, activeUsers: 950, retention: 78 },
    { month: '4月', users: 1420, newUsers: 280, activeUsers: 1200, retention: 88 },
    { month: '5月', users: 1680, newUsers: 320, activeUsers: 1450, retention: 91 },
    { month: '6月', users: 1850, newUsers: 380, activeUsers: 1620, retention: 94 },
  ];

  // 周度数据
  const weeklyData = [
    { week: '第1周', users: 1750, growth: 2.1 },
    { week: '第2周', users: 1780, growth: 1.7 },
    { week: '第3周', users: 1820, growth: 2.2 },
    { week: '第4周', users: 1850, growth: 1.6 },
  ];

  // 用户类型分布
  const userTypes = [
    { type: '新用户', count: 380, percentage: 20.5, color: '#52c41a' },
    { type: '活跃用户', count: 1620, percentage: 87.6, color: '#1890ff' },
    { type: '沉睡用户', count: 230, percentage: 12.4, color: '#faad14' },
    { type: '流失用户', count: 95, percentage: 5.1, color: '#ff4d4f' },
  ];

  // 设备类型分布数据
  const deviceTypes = [
    { type: '移动端', count: 15420, percentage: 68.5, icon: <MobileOutlined />, color: '#1890ff' },
    { type: '桌面端', count: 5680, percentage: 25.2, icon: <DesktopOutlined />, color: '#52c41a' },
    { type: '平板端', count: 1420, percentage: 6.3, icon: <TabletOutlined />, color: '#722ed1' }
  ];

  // 地域分布数据
  const regionData = [
    { region: '华东', users: 8520, percentage: 37.8, growth: 12.5 },
    { region: '华南', users: 6240, percentage: 27.7, growth: 8.3 },
    { region: '华北', users: 4680, percentage: 20.8, growth: 15.2 },
    { region: '西南', users: 2180, percentage: 9.7, growth: 22.1 },
    { region: '其他', users: 900, percentage: 4.0, growth: 5.8 }
  ];

  // 用户活跃度分析
  const activityLevels = [
    { level: '高活跃', count: 3240, percentage: 14.4, color: '#52c41a', description: '日均使用>2小时' },
    { level: '中活跃', count: 8960, percentage: 39.8, color: '#1890ff', description: '日均使用30分钟-2小时' },
    { level: '低活跃', count: 7320, percentage: 32.5, color: '#faad14', description: '日均使用<30分钟' },
    { level: '沉睡', count: 3000, percentage: 13.3, color: '#f5222d', description: '7天未活跃' }
  ];

  const maxValue = Math.max(...monthlyData.map(d => d.users));
  const currentMonth = monthlyData[monthlyData.length - 1];
  const previousMonth = monthlyData[monthlyData.length - 2];
  const growth = ((currentMonth.users - previousMonth.users) / previousMonth.users * 100).toFixed(1);

  // 渲染月度趋势图
  const renderMonthlyChart = () => (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={8}>
            <Statistic
              title="总用户数"
              value={currentMonth.users}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="新增用户"
              value={currentMonth.newUsers}
              prefix={<TeamOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="留存率"
              value={currentMonth.retention}
              suffix="%"
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Col>
        </Row>
      </div>
      
      {/* 趋势图 - 折线图 */}
      <div style={{ 
        position: 'relative',
        height: 140, 
        padding: '20px 8px',
        borderBottom: '1px solid #f0f0f0',
        marginBottom: 16,
        background: 'linear-gradient(180deg, #fafbfc 0%, #ffffff 100%)'
      }}>
        {/* SVG 折线图 */}
        <svg 
          width="100%" 
          height="100%" 
          style={{ position: 'absolute', top: 0, left: 0 }}
          viewBox="0 0 400 140"
        >
          {/* 网格线 */}
          <defs>
            <pattern id="grid" width="66.67" height="28" patternUnits="userSpaceOnUse">
              <path d="M 66.67 0 L 0 0 0 28" fill="none" stroke="#f0f0f0" strokeWidth="0.5"/>
            </pattern>
            <linearGradient id="lineGradient" x1="0%" y1="0%" x2="100%" y2="0%">
              <stop offset="0%" stopColor="#1890ff" />
              <stop offset="100%" stopColor="#52c41a" />
            </linearGradient>
            <linearGradient id="areaGradient" x1="0%" y1="0%" x2="0%" y2="100%">
              <stop offset="0%" stopColor="#1890ff" stopOpacity="0.2" />
              <stop offset="100%" stopColor="#1890ff" stopOpacity="0.05" />
            </linearGradient>
          </defs>
          <rect width="100%" height="100%" fill="url(#grid)" />
          
          {/* 面积填充 */}
          <path
            d={`${monthlyData.map((item, index) => {
              const x = (index / (monthlyData.length - 1)) * 360 + 20;
              const y = 120 - (item.users / maxValue) * 80;
              return `${index === 0 ? 'M' : 'L'} ${x} ${y}`;
            }).join(' ')} L 380 120 L 20 120 Z`}
            fill="url(#areaGradient)"
          />
          
          {/* 折线路径 */}
          <path
            d={monthlyData.map((item, index) => {
              const x = (index / (monthlyData.length - 1)) * 360 + 20;
              const y = 120 - (item.users / maxValue) * 80;
              return `${index === 0 ? 'M' : 'L'} ${x} ${y}`;
            }).join(' ')}
            fill="none"
            stroke="url(#lineGradient)"
            strokeWidth="3"
            strokeLinecap="round"
            strokeLinejoin="round"
            filter="drop-shadow(0 2px 4px rgba(24, 144, 255, 0.2))"
          />
          
          {/* 数据点 */}
          {monthlyData.map((item, index) => {
            const x = (index / (monthlyData.length - 1)) * 360 + 20;
            const y = 120 - (item.users / maxValue) * 80;
            const isLatest = index === monthlyData.length - 1;
            return (
              <g key={index}>
                {/* 外圈光晕 */}
                <circle
                  cx={x}
                  cy={y}
                  r="8"
                  fill={isLatest ? '#1890ff' : '#52c41a'}
                  fillOpacity="0.2"
                />
                {/* 外圈 */}
                <circle
                  cx={x}
                  cy={y}
                  r="6"
                  fill="#fff"
                  stroke={isLatest ? '#1890ff' : '#52c41a'}
                  strokeWidth="3"
                  filter="drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1))"
                />
                {/* 内圈 */}
                <circle
                  cx={x}
                  cy={y}
                  r="3"
                  fill={isLatest ? '#1890ff' : '#52c41a'}
                />
                {/* 动画脉冲效果（仅最新数据点） */}
                {isLatest && (
                  <circle
                    cx={x}
                    cy={y}
                    r="6"
                    fill="none"
                    stroke="#1890ff"
                    strokeWidth="2"
                    opacity="0.6"
                  >
                    <animate
                      attributeName="r"
                      values="6;12;6"
                      dur="2s"
                      repeatCount="indefinite"
                    />
                    <animate
                      attributeName="opacity"
                      values="0.6;0;0.6"
                      dur="2s"
                      repeatCount="indefinite"
                    />
                  </circle>
                )}
              </g>
            );
          })}
          
          {/* Y轴标签 */}
          <g>
            <text x="10" y="25" fontSize="10" fill="#8c8c8c" textAnchor="end">
              {(maxValue * 1.2).toLocaleString()}
            </text>
            <text x="10" y="70" fontSize="10" fill="#8c8c8c" textAnchor="end">
              {(maxValue * 0.6).toLocaleString()}
            </text>
            <text x="10" y="115" fontSize="10" fill="#8c8c8c" textAnchor="end">
              0
            </text>
          </g>
        </svg>
        
        {/* 数据点标签和交互 */}
        <div style={{ 
          position: 'relative', 
          height: '100%', 
          display: 'flex', 
          alignItems: 'end',
          justifyContent: 'space-between',
          paddingTop: 20
        }}>
          {monthlyData.map((item, index) => (
            <Tooltip key={index} 
              title={
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontWeight: 600, marginBottom: 4 }}>{item.month}</div>
                  <div>👥 用户数: {item.users.toLocaleString()}人</div>
                  <div>🆕 新增: {item.newUsers.toLocaleString()}人</div>
                  <div>📈 留存率: {item.retention}%</div>
                </div>
              }
              placement="top"
            >
              <div style={{ 
                display: 'flex', 
                flexDirection: 'column', 
                alignItems: 'center',
                cursor: 'pointer',
                padding: '8px 4px',
                borderRadius: 4,
                transition: 'all 0.3s ease'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = '#f0f8ff';
                e.currentTarget.style.transform = 'translateY(-2px)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = 'transparent';
                e.currentTarget.style.transform = 'translateY(0)';
              }}
              >
                <div style={{ 
                  width: 12, 
                  height: 12, 
                  backgroundColor: 'transparent',
                  marginBottom: 8
                }} />
                <Text style={{ 
                  fontSize: 12, 
                  color: index === monthlyData.length - 1 ? '#1890ff' : '#8c8c8c',
                  fontWeight: index === monthlyData.length - 1 ? 600 : 400,
                  transition: 'all 0.3s ease'
                }}>
                  {item.month}
                </Text>
              </div>
            </Tooltip>
          ))}
        </div>
      </div>
      
      {/* 用户类型分布 */}
      <div style={{ marginBottom: 16 }}>
        <Title level={5} style={{ marginBottom: 12 }}>用户类型分布</Title>
        <Row gutter={[8, 8]}>
          {userTypes.map((type, index) => (
            <Col span={6} key={index}>
              <div style={{ textAlign: 'center', padding: '8px', backgroundColor: '#fafafa', borderRadius: 8 }}>
                <div style={{ fontSize: 18, fontWeight: 600, color: type.color }}>
                  {type.count}
                </div>
                <div style={{ fontSize: 12, color: '#8c8c8c', marginBottom: 4 }}>
                  {type.type}
                </div>
                <Tag color={type.color} style={{ fontSize: 10 }}>
                  {type.percentage}%
                </Tag>
              </div>
            </Col>
          ))}
        </Row>
      </div>

      {/* 设备类型分布 */}
      <div style={{ marginBottom: 16 }}>
        <Title level={5} style={{ marginBottom: 12 }}>设备类型分布</Title>
        <Row gutter={16}>
          {deviceTypes.map((device, index) => (
            <Col span={8} key={index}>
              <Card size="small" style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 24, color: device.color, marginBottom: 8 }}>
                  {device.icon}
                </div>
                <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 4 }}>
                  {device.count.toLocaleString()}
                </div>
                <div style={{ fontSize: 12, color: '#8c8c8c', marginBottom: 8 }}>
                  {device.type}
                </div>
                <Progress 
                  percent={device.percentage} 
                  size="small" 
                  strokeColor={device.color}
                  showInfo={false}
                />
                <div style={{ fontSize: 12, color: device.color, marginTop: 4 }}>
                  {device.percentage}%
                </div>
              </Card>
            </Col>
          ))}
        </Row>
      </div>

      {/* 地域分布 */}
      <div>
        <Title level={5} style={{ marginBottom: 12 }}>地域分布</Title>
        <Row gutter={[16, 8]}>
          {regionData.map((region, index) => (
            <Col span={12} key={index}>
              <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                padding: '8px 12px',
                backgroundColor: '#fafafa',
                borderRadius: 6,
                marginBottom: 8
              }}>
                <div>
                  <div style={{ fontWeight: 600, marginBottom: 2 }}>
                    <GlobalOutlined style={{ marginRight: 6, color: '#1890ff' }} />
                    {region.region}
                  </div>
                  <div style={{ fontSize: 12, color: '#8c8c8c' }}>
                    {region.users.toLocaleString()}人 ({region.percentage}%)
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <Badge 
                    count={`+${region.growth}%`} 
                    style={{ 
                      backgroundColor: region.growth > 15 ? '#52c41a' : region.growth > 10 ? '#1890ff' : '#faad14',
                      fontSize: 10
                    }} 
                  />
                </div>
              </div>
            </Col>
          ))}
        </Row>
      </div>
    </div>
  );

  // 渲染周度趋势图
  const renderWeeklyChart = () => (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Title level={5}>本月周度增长</Title>
      </div>
      
      <Row gutter={16}>
        {weeklyData.map((week, index) => (
          <Col span={6} key={index}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 16, fontWeight: 600, color: '#1890ff' }}>
                {week.users.toLocaleString()}
              </div>
              <div style={{ fontSize: 12, color: '#8c8c8c', marginBottom: 8 }}>
                {week.week}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {week.growth > 0 ? (
                  <RiseOutlined style={{ color: '#52c41a', fontSize: 12, marginRight: 4 }} />
                ) : (
                  <FallOutlined style={{ color: '#ff4d4f', fontSize: 12, marginRight: 4 }} />
                )}
                <Text style={{ 
                  fontSize: 12, 
                  color: week.growth > 0 ? '#52c41a' : '#ff4d4f',
                  fontWeight: 500
                }}>
                  {week.growth > 0 ? '+' : ''}{week.growth}%
                </Text>
              </div>
            </Card>
          </Col>
        ))}
      </Row>
      
      <div style={{ marginTop: 16 }}>
        <Title level={5}>增长趋势分析</Title>
        <div style={{ padding: 16, backgroundColor: '#f6f8fa', borderRadius: 8 }}>
          <Row gutter={16}>
            <Col span={12}>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 24, fontWeight: 600, color: '#52c41a' }}>
                  +{((weeklyData[weeklyData.length - 1].users - weeklyData[0].users) / weeklyData[0].users * 100).toFixed(1)}%
                </div>
                <Text type="secondary">月度总增长</Text>
              </div>
            </Col>
            <Col span={12}>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 24, fontWeight: 600, color: '#1890ff' }}>
                  {(weeklyData.reduce((sum, week) => sum + week.growth, 0) / weeklyData.length).toFixed(1)}%
                </div>
                <Text type="secondary">平均周增长</Text>
              </div>
            </Col>
          </Row>
        </div>
      </div>

      {/* 用户活跃度分析 */}
      <div style={{ marginTop: 16 }}>
        <Title level={5}>用户活跃度分析</Title>
        <Row gutter={[16, 16]}>
          {activityLevels.map((level, index) => (
            <Col span={12} key={index}>
              <Card size="small" style={{ height: '100%' }}>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                  <div style={{ 
                    width: 12, 
                    height: 12, 
                    backgroundColor: level.color, 
                    borderRadius: '50%',
                    marginRight: 8
                  }} />
                  <Text strong>{level.level}</Text>
                  <Badge 
                    count={level.count.toLocaleString()} 
                    style={{ backgroundColor: level.color, marginLeft: 'auto' }}
                  />
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Progress 
                    percent={level.percentage} 
                    strokeColor={level.color}
                    size="small"
                    format={() => `${level.percentage}%`}
                  />
                </div>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  {level.description}
                </Text>
              </Card>
            </Col>
          ))}
        </Row>
      </div>
    </div>
  );

  return (
    <Card
      loading={loading}
      title={
        <Space>
          <LineChartOutlined style={{ color: '#1890ff' }} />
          <span>用户增长趋势</span>
        </Space>
      }
      extra={
        <Space>
          <ArrowUpOutlined style={{ color: '#52c41a', fontSize: 12 }} />
          <Text style={{ color: '#52c41a', fontSize: 12 }}>+{growth}%</Text>
        </Space>
      }
      style={{ height: '100%' }}
    >
      <Tabs 
        defaultActiveKey="monthly" 
        onChange={(key) => setActiveTab(key)}
        items={[
          {
            key: 'monthly',
            label: '月度趋势',
            children: renderMonthlyChart()
          },
          {
            key: 'weekly',
            label: '周度分析',
            children: renderWeeklyChart()
          }
        ]}
      />
    </Card>
  );
};

export default UserTrendChart;